package com.reggie.common;

import com.reggie.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
/**
 * 全局异常处理器
 */
public class GlobalExceptionHandler {
    /**
     * 处理重复添加异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handle(SQLIntegrityConstraintViolationException ex) {
        log.error("GlobalExceptionHandler::handle error", ex);
        String msg = ex.getMessage();
        if (msg.contains("Duplicate entry")) {
            //肯定是重复
            return R.error(msg.split(" ")[2] + "已存在，无法新增");
        }
        return R.error("服务器开小差了");
    }

    /**
     * 处理自定义的异常：当前分类下有菜品或者套餐的时候不能被删除，抛这个异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
